import React, { useState } from 'react';
import { Table } from 'antd';
import { DndContext, DragOverlay, useDroppable } from '@dnd-kit/core';
import { ContentStyle, ScrollableStyle, ItemStyle } from './style';
import { columns, list } from './config';
import Draggable from './Draggable';
import type { DragStartEvent, DragEndEvent } from '@dnd-kit/core';

// 自定义行
interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
	'data-row-key': string;
}
export const Row = (props: RowProps) => {
	const { isOver, setNodeRef } = useDroppable({
		id: props['data-row-key'],
		data: { record: props.children[0].props.record }
	});

	return (
		<tr {...props} ref={setNodeRef} className={isOver ? 'is-over' : undefined}>
			{props.children}
		</tr>
	);
};

const TableDragOverlay = () => {
	const [items] = useState(['1', '2', '3', '4', '5']);
	const [activeId, setActiveId] = useState(null);

	function handleDragStart(event: DragStartEvent) {
		setActiveId(event.active.id);
	}

	function handleDragEnd(event: DragEndEvent) {
		const { active, over } = event;
		setActiveId(null);
		console.log('handleDragEnd: ', active, over);
	}

	return (
		<DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
			<ContentStyle>
				<div className="dnd">
					<ScrollableStyle>
						{items.map((id) => (
							<Draggable key={id} id={id}>
								{id}
							</Draggable>
						))}
					</ScrollableStyle>

					<DragOverlay dropAnimation={null}>
						{activeId ? <ItemStyle>嘿嘿：{activeId}</ItemStyle> : null}
					</DragOverlay>
				</div>
				<div className="table">
					<Table
						rowKey="key"
						components={{ body: { row: Row } }}
						columns={columns}
						dataSource={list}
						pagination={false}
					/>
				</div>
			</ContentStyle>
		</DndContext>
	);
};

const DragOverlayContext = () => {
	return <TableDragOverlay />;
};

export default DragOverlayContext;
